package com.lmaos.allcontrol.beancontrol.class_;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 
 * @author lmaos
 *
 * <p>作者：张星宇</p>
 * <p>时间：2017年12月28日 下午4:31:53</p>
 * <p>说明:我的class加载器,自定义一个加载器		</p>
 *
 */
public class MyClassLoader extends URLClassLoader{
	protected Map<String, Class> classMap = new ConcurrentHashMap<String, Class>();
	private File classpath;
	/** 指定 classpath创建加载器
	 * 
	 * @param classpath
	 */
	public MyClassLoader(File classpath) {
		super(ClassLoaderUtils.getClasspathFileURLs(classpath));
		setClasspath(classpath);
	}
	public MyClassLoader(String classpath){
		this(new File(classpath));
	}
	/** 优先指定加载jar源,之后从classpath查找源
	 * 
	 * @param urls
	 * @param classpath
	 */
	public MyClassLoader(URL[] urls, File classpath) {
		super(ClassLoaderUtils.getClasspathFileURLs(urls,classpath));
		setClasspath(classpath);
	}

	@Override
	public void addURL(URL url) {
		super.addURL(url);
	}
	
	@Override
	public Class<?> findClass(String name) throws ClassNotFoundException {
		Class cl = classMap.get(name);
		if(cl==null){
			 cl = super.findClass(name);
			 classMap.put(name, cl);
		}
		return cl;
	}
	/** 获取当前 name 指定的 class,不存在则返回null
	 * 
	 * @param name
	 * @return
	 */
	public Class getClassByName(String name){
		Class cl = null;
		try {
			cl = this.findClass(name);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return cl;
	}
	public MyClassLoader() {
		super(new URL[0]);
	}
	public void setClasspath(File classpath) {
		if(!classpath.exists()){
			classpath.mkdirs();
		}
		this.classpath = classpath;
	}
	public File getClasspath() {
		return classpath;
	}
	public File getClasspath(String name) {
		if(classpath!=null){
			if(name==null||name.isEmpty()||name.equals(".")){
				return classpath;
			}
			File resurceFile = new File(classpath, name);
			if(resurceFile.exists()){
				return resurceFile;
			}
		}
		return null;
	}
	@Override
	public URL getResource(String name) {
		try {
			File resurceFile = getClasspath(name);
			if(resurceFile!=null){
				return resurceFile.toURI().toURL();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.getResource(name);
	}
	@Override
	public InputStream getResourceAsStream(String name) {
		try {
			File resurceFile = getClasspath(name);
			if(resurceFile!=null){
				return new FileInputStream(resurceFile);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.getResourceAsStream(name);
	}
	
}
